package com.czk.socket;

import org.junit.Test;

import java.io.IOException;
import java.net.InetSocketAddress;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.nio.channels.ServerSocketChannel;
import java.nio.channels.SocketChannel;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.nio.file.StandardOpenOption;

/**
 * @Author:ChenZhangKun
 * @Date: 2021/1/10 11:50
 */
public class BlockingNIO2Test {
    @Test
    public void client() throws IOException {
        SocketChannel socketChannel = SocketChannel.open(new InetSocketAddress("127.0.0.1", 9898));
        FileChannel fileChannel = FileChannel.open(Paths.get("D:\\简历\\罗琴.doc"), StandardOpenOption.READ);
        ByteBuffer allocate = ByteBuffer.allocate(1024);
        while (fileChannel.read(allocate)!=-1){
            allocate.flip();
            socketChannel.write(allocate);
            allocate.clear();
        }
        // 告诉服务器写完了
        socketChannel.shutdownOutput();
        // 接收服务端的反馈
        int len=0;
        while ((len=socketChannel.read(allocate))!=-1){
            allocate.flip();
            System.out.println(new String(allocate.array(),0,len));
            allocate.clear();
        }

        fileChannel.close();
        socketChannel.close();
    }
    @Test
    public void server() throws IOException {
        // 创建服务端socket
        ServerSocketChannel serverSocketChannel=ServerSocketChannel.open();
        // 绑定端口号
        serverSocketChannel.bind(new InetSocketAddress(9898));
        /// 接收数据
        SocketChannel accept = serverSocketChannel.accept();
        // 创见写入缓冲区
        ByteBuffer byteBuffer=ByteBuffer.allocate(1024);
        // 写入地区
        FileChannel open = FileChannel.open(Paths.get("D:\\简历\\1\\5.doc"), StandardOpenOption.READ, StandardOpenOption.WRITE, StandardOpenOption.CREATE);
        while (accept.read(byteBuffer)!=-1){
            byteBuffer.flip();
            open.write(byteBuffer);
            byteBuffer.clear();
        }
        // 发送反馈给客户端
        byteBuffer.put("服务端接收客户端数据成功".getBytes());
        byteBuffer.flip();
        // 协会客户端
        accept.write(byteBuffer);
        open.close();
        accept.close();
        serverSocketChannel.close();

    }
}
